/**
 * 
 */
package com.xbang.core.web.converter;

import java.util.Date;
import java.util.Map;

import ognl.DefaultTypeConverter;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xbang.core.page.Page;

/**
 * @author dev.zhang
 * 
 */
public class PageConverter extends DefaultTypeConverter {

	private static final Log logger = LogFactory.getLog(PageConverter.class);

	/**
	 * Convert value between types
	 */
	@SuppressWarnings("unchecked")
	public Object convertValue(Map ognlContext, Object value, Class toType) {
		Object result = null;
		if (toType == Page.class) {
			result = doConvertToPage(value);
		} else if (toType == String.class) {
			result = doConvertToString(value);
		}
		return result;
	}

	/**
	 * Convert String to Page
	 * 
	 * @param value
	 * @return
	 */
	private Page doConvertToPage(Object value) {
		Page result = null;

		if (value instanceof String) {
			result = new Page();

			if (NumberUtils.isNumber((String) value)) {
				result.setCurrentPage(new Integer((String) value));
			}

		} else if (value instanceof Object[]) {
			// let's try to convert the first element only
			Object[] array = (Object[]) value;

			if ((array != null) && (array.length >= 1)) {
				value = array[0];
				result = doConvertToPage(value);
			}

		} else if (Page.class.isAssignableFrom(value.getClass())) {
			result = (Page) value;
		}
		return result;
	}

	/**
	 * Convert Page to String
	 * 
	 * @param value
	 * @return
	 */
	private String doConvertToString(Object value) {
		String result = null;
		if (value instanceof Date) {
			result = value.toString();
		}
		return result;
	}

}
